package com.xyc.servlet.user;

import com.xyc.mapper.UserMapper;
import lombok.SneakyThrows;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import static java.lang.Integer.parseInt;

@WebServlet("/addUserReal")
public class AddUserRealServlet extends HttpServlet {

    @SneakyThrows
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws UnsupportedEncodingException {
        req.setCharacterEncoding("utf-8");
        //从addUser.jsp中获取添加上去的数据,id自动生成，并添加至数据中，再返回上一级myUser
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        String user_id = UUID.randomUUID().toString().replaceAll("-", "");
        String user_name = req.getParameter("user_name");
        String sex = req.getParameter("sex");
        int age = parseInt(req.getParameter("age"));
        String email = req.getParameter("email");
        int isVip = Integer.parseInt(req.getParameter("isVip"));
        int isUse = Integer.parseInt(req.getParameter("isUse"));
        Date create_time = sdf.parse(req.getParameter("create_time"));
        Date last_time = sdf.parse(req.getParameter("last_time"));

        Map map = new HashMap();
        map.put("user_name", user_name);
        map.put("age", age);
        map.put("sex", sex);
        map.put("isVip", isVip);
        map.put("isUse", isUse);
        map.put("email", email);
        map.put("create_time", create_time);
        map.put("last_time", last_time);
        map.put("user_id", user_id);

        ApplicationContext ctx = new ClassPathXmlApplicationContext("spring-dao.xml");
        UserMapper userMapper = ctx.getBean("userMapper", UserMapper.class);
        userMapper.addUser(map);

        req.getRequestDispatcher("myUser").forward(req, resp);
    }
}
